// CountPOAServerWithActivator.java: The Count Server main program
package Server2;

import org.omg.PortableServer.*;
import org.omg.CosNaming.*;

import java.io.*;

class CountPOAServerWithActivator
{ 
	final static int activeServantLimit = 500;
	
	static public void main(String[] args) {
		
	try
    { // Initialize the ORB
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);

      // get a reference to the root POA
      POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

      // Create policies for our persistent POA
      org.omg.CORBA.Policy[] policies = {
		  rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT),
		  rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID),
		  rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.RETAIN),
		  rootPOA.create_request_processing_policy(RequestProcessingPolicyValue.USE_SERVANT_MANAGER)
      };

      // Create myPOA with the right policies
      final POA myPOA = rootPOA.create_POA( "count_poa", rootPOA.the_POAManager(), policies );

      // Activate the POA manager
      rootPOA.the_POAManager().activate();
      
      // Assign the servant manager
      CountManagerActivator mgr = new CountManagerActivator(activeServantLimit);
      myPOA.set_servant_manager( mgr._this(orb) );

      // get a reference to the Naming Service root context
      org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
      
      if (nameServiceObj == null)
      {
        System.out.println("nameServiceObj = null");
        return;
      }

      NamingContextExt nameService = NamingContextExtHelper.narrow(nameServiceObj);
      if (nameService == null)
      {
        System.out.println("nameService = null");
        return;
      }

      
      //creating array of 1000 objects to hold Count object references
		org.omg.CORBA.Object[] countObjects = new org.omg.CORBA.Object[1000];
		
      long startTime = System.currentTimeMillis();
		
	   // Generate 1000 Object References, but _not_ a servant (yet).
      for (int x = 0; x < 1000; x++) {
          // Decide on the ID for the servant
    	  final byte[] countId = "MyCount".concat(String.valueOf(x+1)).getBytes();
    	  countObjects[x] = myPOA.create_reference_with_id(countId, CounterPOA.CountHelper.type().id() );
      }
      
      long stopTime = System.currentTimeMillis();
      
      for (int x = 0; x < 1000; x++) {
    	  	//creates the .state files to store the sums
			FileOutputStream f_Out = new FileOutputStream("MyCount" + String.valueOf(x+1) + ".state");
			PrintWriter b_Out = new PrintWriter(new OutputStreamWriter(f_Out));
			b_Out.println(0);
			b_Out.close();
			f_Out.close();

			// bind the Count object in the Naming service
			NameComponent[] countName = {new NameComponent("countName".concat(String.valueOf(x+1)), "")};
			nameService.rebind(countName, countObjects[x]);
      }
      
      System.out.println("Avg. time to create each counter = " + ((stopTime - startTime)/1000000f) + " msecs");
      System.out.println("Waiting for client requests...................");

//      try
//	  {
//	      PrintWriter p_Out = new PrintWriter(new FileOutputStream("ior.txt"));
//	      p_Out.println(orb.object_to_string(countObj));
//	      p_Out.close();
//	  }
//      catch(IOException IOe)
//	  {
//
//	  }

      // after 15 seconds, deactivate the object.
      //
      // the POA will call etherealize(..) on the ServantActivator
      // which will write the state to a file.
      //
      // this activity repeats every 15 seconds.
//      new Thread(
//		 new Runnable()
//		 {
//		     public void run()
//		     {
//		    	 for(;;)
//				     try
//					 {
//					     Thread.sleep(15000);
//	
//					     System.out.println("...deactivating count object");
//					     myPOA.deactivate_object( countId );
//					 }
//				 	 catch(org.omg.PortableServer.POAPackage.ObjectNotActive Ex)
//				     {
//				 		System.out.println("...(the object was already deactivated)");
//				     }
//				 	catch(Exception x)
//				     {
//				     }
//
//
//		     }
//		 }
//		 ).start();

	      // Wait for incoming requests
	      orb.run();

    } catch(Exception e)
    { System.err.println(e);
    }
  }
}
